<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加角色按钮区域 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="dialogVisible = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>

      <!-- 角色列表区域 -->
      <el-table :data="rolesList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template #default="{ row }">
            <el-row
              v-for="(item1, index1) in row.children"
              :key="index1"
              class="bdbottom"
              :class="index1 === 0 ? 'bdtop' : ''"
              type="flex"
              align="middle"
            >
              <!-- 一级权限 -->
              <el-col :span="6">
                <el-tag closable @close="removeRightById(row, item1.id)">{{
                  item1.authName
                }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级和三级权限 -->
              <el-col :span="18">
                <el-row
                  v-for="(item2, index2) in item1.children"
                  :key="index2"
                  :class="index2 === 0 ? '' : 'bdtop'"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="(item3, index3) in item2.children"
                      :key="index3"
                      closable
                      @close="removeRightById(row, item3.id)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <pre>
              {{ row }}
            </pre>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"> </el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column label="操作" width="300px">
          <template #default="{ row }">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(row.id)"
              >编辑</el-button
            ><el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeRoleById(row.id)"
              >删除</el-button
            ><el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="showSetRightDialog(row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色对话框区域 -->
    <el-dialog
      title="添加角色"
      :visible.sync="dialogVisible"
      width="50%"
      @close="addDialogClose"
    >
      <!-- 内容主体区域 -->
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addFormRules"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色对话框区域 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="$refs.editFormRef.resetFields()"
    >
      <!-- 内容主体区域 -->
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editFormRules"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRole">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限对话框区域 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="setRightDialogClosed"
    >
      <!-- 树形控件 -->
      <el-tree
        :data="rightsList"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defaultCheckedArray"
        ref="treeRef"
      ></el-tree>
      <!-- node-key="id" 对应的是rightsList中的id -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getRolesListApi, addRoleApi, getRoleApi, editRoleApi, removeRoleApi } from '../../api/roles'
import { removeRightByIdApi, getRightsApi, allotRightsApi } from '../../api/rights'
export default {
  data () {
    return {
      // 所有角色列表数据
      rolesList: [],
      // 控制添加角色对话框隐藏与显示
      dialogVisible: false,
      // 添加角色的表单数据
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      // 添加角色的表单验证规则
      addFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ]
      },
      // 控制编辑角色对话框隐藏与显示
      editDialogVisible: false,
      // 编辑角色的表单数据
      editForm: {},
      // 编辑角色的表单验证规则
      editFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ]
      },
      // 控制分配权限对话框的显示与隐藏
      setRightDialogVisible: false,
      // 所有权限的数据
      rightsList: [],
      // 树形控件的属性绑定对象
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      // 默认勾选的节点的Id值数组
      defaultCheckedArray: [],
      // 分配权限的角色Id
      roleId: ''
    }
  },
  methods: {
    // 获取角色列表
    async getRolesList () {
      const { data } = await getRolesListApi()
      // console.log(data)
      if (data.meta.status !== 200) return this.$message.error('获取角色列表失败!')
      this.rolesList = data.data
    },
    // 监听添加角色dialog的关闭事件
    addDialogClose () {
      this.$refs.addFormRef.resetFields()
      this.addForm.roleDesc = ''
    },
    // 添加角色
    addRole () {
      this.$refs.addFormRef.validate(async valid => {
        // console.log(valid)
        if (!valid) return false
        const { data } = await addRoleApi(this.addForm)
        // console.log(data)
        if (data.meta.status !== 201) {
          this.$message.error('添加角色失败!')
        }
        this.$message.success('添加角色成功!')
        this.getRolesList()
        this.dialogVisible = false
      })
    },
    // 展示编辑角色的对话框
    async showEditDialog (id) {
      // console.log(id)
      this.editDialogVisible = true
      const { data } = await getRoleApi(id)
      // console.log(data)
      if (data.meta.status !== 200) {
        return this.$message.error('获取编辑角色信息失败!')
      }
      this.editForm = data.data
    },
    // 提交编辑信息
    editRole () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return false
        const { data } = await editRoleApi(this.editForm.roleId, this.editForm.roleName, this.editForm.roleDesc)
        // console.log(data)
        if (data.meta.status !== 200) return this.$message.error('编辑角色失败!')
        this.$message.success('编辑角色成功!')
        this.editDialogVisible = false
        this.getRolesList()
      })
    },
    // 删除角色
    async removeRoleById (id) {
      // console.log(id)
      const { data } = await removeRoleApi(id)
      // console.log(data)
      if (data.meta.status !== 200) return this.$message.error('删除角色失败!')
      this.$message.success('删除角色成功!')
      this.getRolesList()
    },
    // 根据Id删除对应的tag
    async removeRightById (role, rightId) {
      // console.log(roleId, rightId)
      // const confirmResult = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // }).catch(error => error)
      // if (confirmResult !== 'confirm') {
      //   return this.$message.info('取消了删除')
      // }
      // const { data } = await removeRightByIdApi(role.id, rightId)
      // // console.log(data)
      // if (data.meta.status !== 200) {
      //   return this.$message.error('删除失败!')
      // }
      // this.$message.success('删除成功')
      // this.getRolesList()
      // 直接调用获取用户的方法会导致展开栏的关闭,这样体验不好
      // 可以直接把返回的最新数据直接赋值
      // 在传参时,传入row而不是row.id
      // role.children = data.data

      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data } = await removeRightByIdApi(role.id, rightId)
        // console.log(data)
        if (data.meta.status !== 200) return this.$message.error('删除失败！')
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        // this.getRolesList()
        role.children = data.data
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 展示分配权限的对话框
    async showSetRightDialog (role) {
      // 分配角色时要是用角色id,在这里先保存
      this.roleId = role.id
      // 获取所有权限的数据
      const { data } = await getRightsApi('tree')
      // console.log(data)
      if (data.meta.status !== 200) return this.$message.error('获取所有权限失败!')
      // 保存获取到的权限
      this.rightsList = data.data
      // 递归获取三级权限节点的Id
      this.getLeafKeys(role, this.defaultCheckedArray)
      this.setRightDialogVisible = true
    },
    // 通过递归遍历的形式,获取角色下所有三级权限的id,并保存到defaultCheckedArray数组
    getLeafKeys (node, arr) {
      // 如果当前node节点不包含children属性,则是三级几点
      if (!node.children) {
        // 遍历每一个权限节点,如果当前节点是三级节点就保存到数组arr
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        return this.getLeafKeys(item, arr)
      })
    },
    // 监听分配权限对话框的关闭事件
    setRightDialogClosed () {
      this.defaultCheckedArray = []
    },
    // 点击确认为角色分配权限的函数
    async allotRights () {
      // 获取所有全选和半全选节点的id
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      // console.log(keys)
      const idStr = keys.join(',')
      const { data } = await allotRightsApi(this.roleId, idStr)
      console.log(data)
      if (data.meta.status !== 200) return this.$message.error('用户权限分配失败!')
      this.$message.success('权限分配成功!')
      this.getRolesList()
      this.setRightDialogVisible = false
    }
  },
  created () {
    this.getRolesList()
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
</style>
